package com.yst.webplugin.annotation;

import org.springframework.http.HttpHeaders;
import org.springframework.http.server.ServerHttpAsyncRequestControl;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.security.Principal;
import java.util.Enumeration;

public class Request implements ServerHttpRequest {

    private final HttpServletRequest request;

    public Request(HttpServletRequest request){
        this.request=request;
    }

    @Override
    public Principal getPrincipal() {
        return request.getUserPrincipal();
    }

    @Override
    public InetSocketAddress getLocalAddress() {
        return new InetSocketAddress(request.getLocalAddr(),request.getLocalPort());
    }

    @Override
    public InetSocketAddress getRemoteAddress() {
        return new InetSocketAddress(request.getRemoteAddr(),request.getRemotePort());
    }

    @Override
    public ServerHttpAsyncRequestControl getAsyncRequestControl(ServerHttpResponse response) {
        return null;
    }


    @Override
    public InputStream getBody() throws IOException {
        return request.getInputStream();
    }

    @Override
    public String getMethodValue() {
        return request.getMethod();
    }

    @Override
    public URI getURI() {
        return URI.create(request.getRequestURI());
    }

    @Override
    public HttpHeaders getHeaders() {
        HttpHeaders httpHeaders=new HttpHeaders();
        Enumeration<String> headers=request.getHeaderNames();
        while (headers.hasMoreElements()){
            String key=headers.nextElement();
            httpHeaders.add(key,request.getHeader(key));
        }
        return httpHeaders;
    }
}
